package com.un.web.gpt;

import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.un.core.common.R;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author xingjian
 * @Date 2023-03-23
 **/

@RestController
@RequestMapping("gpt")
public class HousemaidAssistant {
    String apiKey = "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";


    @RequestMapping("content")
    public R getMsg(String msg){
        return R.success(sendMsg(msg));
    }

    public Object sendMsg(String msg) {
        // 消息列表
        List<ChatMessage> list = new ArrayList<>();
        // 给chatGPT定义一个身份，是一个助手
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setRole("system");
        chatMessage.setContent(msg);
        list.add(chatMessage);

        // 定义一个用户身份，content是用户写的内容
        ChatMessage userMessage = new ChatMessage();
        userMessage.setRole("user");
        userMessage.setContent("hello");
        list.add(userMessage);

        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .messages(list)
                .model("gpt-3.5-turbo")
                .build();
        List<ChatCompletionChoice> choices = null;
        try {
            OpenAiService service = new OpenAiService(apiKey);
            // chatCompletion 对象就是chatGPT响应的数据了
            ChatCompletionResult chatCompletion = service.createChatCompletion(request);
            choices = chatCompletion.getChoices();
        } catch (Exception e) {
            return "会话超时";
        }
       // choices.forEach(item-> System.out.println(item.getMessage()));
        return choices.get(0).getMessage().getContent();
    }
}
